import redis from "@/utils/redis.mjs";
// 示例数据结构
class VerificationCode {
    constructor(scene, phoneNumber, code, expiresAt, attempts) {
        this.scene = scene; // 场景值
        this.phoneNumber = phoneNumber; // 手机号码
        this.code = code; // 验证码
        this.expiresAt = expiresAt; // 过期时间
        this.attempts = attempts; // 尝试次数
    }
}
export async function setVerificationCode(phoneNumber, scene, code, expiresInSeconds, maxAttempts) {
    let key = `verification:${scene}:${phoneNumber}`;
    let now = new Date().getTime();
    let expiresAt = now + expiresInSeconds * 1000;
    let attempts = 0;
    let verificationCode = new VerificationCode(
        scene,
        phoneNumber,
        code,
        expiresAt,
        attempts
    );
    try {
        await new Promise((resolve, reject) => {
            redis.set(key, JSON.stringify(verificationCode), 'EX', expiresInSeconds, (err, result) => {
                if (err) reject(err);
                resolve(result);
            });
        });
    } catch (error) {
        throw error;
    }
}

export async function getVerificationCode(phoneNumber, scene) {
    let key = `verification:${scene}:${phoneNumber}`;
    return new Promise((resolve, reject) => {
        redis.get(key, (err, data) => {
            if (err) reject(err);
            if (!data) resolve(null);
            else resolve(JSON.parse(data));
        });
    });
}
async function sendSmsCode () {}
export async function sendVerificationCode(phoneNumber, scene, code, expiresInSeconds, maxAttempts) {
    let verificationCode = {}
    try {
        verificationCode = await getVerificationCode(phoneNumber, scene);

    } catch (e) {
        throw new Error('getVerificationCode error');
    }
    if (verificationCode && verificationCode.attempts >= maxAttempts) {
        throw new Error('Too many attempts, locked.');
    }


    if (verificationCode) {
        verificationCode.attempts += 1;
        // todo 更新缓存
    } else {
        console.log(1)
        await setVerificationCode(phoneNumber, scene, code, expiresInSeconds, maxAttempts);

        // 假设 sendSmsCode 是一个返回 Promise 的函数
        await sendSmsCode(phoneNumber, code);
    }
}
export async function validateVerificationCode(phoneNumber, scene, providedCode) {
    let verificationCode = await getVerificationCode(phoneNumber, scene);
    console.log(verificationCode, providedCode)
    if (!verificationCode || verificationCode.expiresAt < Date.now() || verificationCode.code !== providedCode) {
        throw new Error('Invalid or expired verification code.');
    } else {
        return true;
    }
}
export function generateRandomFourDigit() {
    return Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
}
